package com.erp.erp_ui.Customer2;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Customer2.Customer2Entity;
import com.erp.erp_entitys.Customer2.Customer2Example;
import com.erp.erp_entitys.Customer2.Customer2VoEntity;
import com.erp.erp_entitys.Customer2.req.supAccDeCollReq;
import com.erp.erp_entitys.Customer2.req.supAmountAndPurAmountReq;
import com.erp.erp_entitys.Customer2.res.supAccDeCollRes;
import com.erp.erp_entitys.Customer2.res.supAmountAndPurAmountRes;
import com.erp.erp_entitys.Customer2Log.Customer2LogEntity;
import com.erp.erp_entitys.CustomerShare.CustomerShareEntity;
import com.erp.erp_entitys.CustomerShare.CustomerShareExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Message.MessageEntity;
import com.erp.erp_entitys.Message.MessageExample;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.User.UserEntityExample;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.Customer2.ICustomer2Service;
import com.erp.erp_servers.Customer2Log.ICustomer2LogService;
import com.erp.erp_servers.CustomerShare.ICustomerShareService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.ProcessCustomer2.IProcessCustomer2Service;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_ui.Message.req.EditMessageReq;
import com.erp.erp_ui.Message.service.MessageAllService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.vo.SelectVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 客户
 * @ClassName CustomerControl
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-07-03 23:07
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping(value = "customer2")
public class Customer2Control extends Base {
    @Autowired
    ICustomer2Service customerService;
    @Autowired
    ICustomerService customer;
    @Autowired
    IUserService userService;
    @Autowired
    ICustomer2LogService customerLogService;
    @Autowired
    ICustomerShareService customerShareService;
    @Autowired
    IProcessCustomer2Service processCustomerService;

    /**
     * 消息接口
     */
    @Autowired
    MessageAllService messageAllService;
    /**
     * 字典接口
     */
    @Autowired
    IDictionary2Service dictionary2Service;

    /**
     * 获了当前登陆者所管理的客户信息
     * @param
     * @return
     */
    @RequestMapping(value = "selectByPage")
    @ResponseBody
    public  R<List<Customer2VoEntity>> selectByPage(String name, String type,String saleman,String flag){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            if(StringUtils.isNotEmpty(flag) && flag.equals("kzt")){
                List<String> likzt=new ArrayList<>();
                Map<String, Object> hz = customer.getHZ2(user);
                long total=0;
                switch (type){
                    case "1"://
                        likzt=(List<String>)hz.get("suplierType1List");
                        total=Long.parseLong(hz.get("suplierType1").toString());
                        break;
                    case "2":
                        likzt=(List<String>)hz.get("suplierType2List");
                        total=Long.parseLong(hz.get("suplierType2").toString());
                        break;
                    case "3":
                        likzt=(List<String>)hz.get("suplierType3List");
                        total=Long.parseLong(hz.get("suplierType3").toString());
                        break;
                    case "4":
                        likzt=(List<String>)hz.get("suplierType4List");
                        total=Long.parseLong(hz.get("suplierType4").toString());
                }
                Customer2Example examplekzt=new Customer2Example();
                Customer2Example.Criteria criteriakzt = examplekzt.createCriteria();
                criteriakzt.andCodeIn(likzt);
                List<Customer2Entity> customerEntities = customerService.selectByExample(examplekzt);
                if(customerEntities.size()>10){
                    for (int i=10;i<customerEntities.size();i++){
                        customerEntities.remove(i);
                    }
                }
                List<Integer> li=new ArrayList<>();
                Map<String,String> map=userService.selectAll();
                for(int i=0;i<customerEntities.size();i++){
                    Customer2Entity customers = customerEntities.get(i);
                    customers.setSalesman(map.get(customers.getSalesman()));
                    li.add(customers.getId());
                }
                /////////////////////////
                R<List<Customer2Entity>> build = R.build(customerEntities);

               /* ProcessCustomer2Example example=new ProcessCustomer2Example();
                ProcessCustomer2Example.Criteria criteria = example.createCriteria();
                criteria.andCustomeridIn(li);
                List<ProcessCustomer2Entity> processCustomer2Entities = processCustomerService.selectByExample(example);
                Map<Integer,String> pmp=new HashMap<>();
                for(int i=0;i<processCustomer2Entities.size();i++){
                    pmp.put(processCustomer2Entities.get(i).getCustomerid(),processCustomer2Entities.get(i).getProcessid());
                }*/
                List<Customer2VoEntity> list=new ArrayList<>();
                for(int i=0;i<customerEntities.size();i++){
                    Customer2VoEntity vo=new Customer2VoEntity();
                    vo=vo.conver(customerEntities.get(i));
                   // vo.setProcessid(pmp.get(vo.getId()));
                    list.add(vo);
                }
                R<List<Customer2VoEntity>> build1 =R.build(list);
                build1.setTotal(total);
                build1.setCount(total);
                build1.setStatus(200);
                build1.setCode(0);
                return build1;
            }

            String codes="   SELECT REPLACE(CODE,'\"','') CODE  FROM  customer_share WHERE usercode LIKE '%"+user.getCode()+"%' AND TYPE=2";
            if(name==null){
                name="";
            }
            if(type==null) type="";
            if(saleman==null) saleman="";

            Customer2Entity ce=new Customer2Entity();
            ce.setName(name);
            ce.setType(type);
            //String salesman="";


            //if(! isAdmin(user)){//不是管理员
               // codes=getcodes(user.getCode());
               // ce.setSalesman(user.getCode());
            //}else{
                ce.setSalesman(saleman);
            //}
            ce.setCode(codes);
            //salesman=user.getCode();
           /* Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andSalesmanLike("%"+salesman+"%");
            criteria.andNameLike("%"+name+"%");
            criteria.andTypeLike("%"+type+"%");*/
            List<Customer2Entity> customerEntities = customerService.selectByMap(ce);
            List<Integer> li=new ArrayList<>();
            Map<String,String> map=userService.selectAll();
            for(int i=0;i<customerEntities.size();i++){
                Customer2Entity customers = customerEntities.get(i);
                customers.setSalesman(map.get(customers.getSalesman()));
                li.add(customers.getId());
            }
            /////////////////////////
            R<List<Customer2Entity>> build = R.build(customerEntities);

            /*ProcessCustomer2Example example=new ProcessCustomer2Example();
            ProcessCustomer2Example.Criteria criteria = example.createCriteria();
            criteria.andCustomeridIn(li);
            List<ProcessCustomer2Entity> processCustomer2Entities = processCustomerService.selectByExample(example);
            Map<Integer,String> pmp=new HashMap<>();
            for(int i=0;i<processCustomer2Entities.size();i++){
                pmp.put(processCustomer2Entities.get(i).getCustomerid(),processCustomer2Entities.get(i).getProcessid());
            }*/
            List<Customer2VoEntity> list=new ArrayList<>();
            for(int i=0;i<customerEntities.size();i++){
                Customer2VoEntity vo=new Customer2VoEntity();
                vo=vo.conver(customerEntities.get(i));
               // vo.setProcessid(pmp.get(vo.getId()));
                list.add(vo);
            }
            R<List<Customer2VoEntity>> build1 = R.build(list);
            build1.setMsg(build.getMsg());
            build1.setStatus(build.getStatus());
            build1.setCount(build.getCount());
            build1.setCode(build.getCode());
            build1.setTotal(build.getTotal());
            return build1;
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 公共池
     * @return
     */
    @RequestMapping(value = "select3ByPage")
    @ResponseBody
    public R<List<Customer2Entity>> select3ByPage(String name,String type){
        try{
           // UserEntity user = (UserEntity)this.getBean("user");
            //查询公共池
           /* CustomerPoolExample example=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria = example.createCriteria();
            criteria.andSalesmanEqualTo("");
            List<CustomerPoolEntity> customerPoolEntities = customerPoolService.selectByExample(example);
            List<String> list=new ArrayList<String>();
            for(int i=0;i<customerPoolEntities.size();i++){
                list.add(customerPoolEntities.get(i).getCode());
            }*/
            //根据code获取客户
            Customer2Example example2=new Customer2Example();
            Customer2Example.Criteria criteria2 = example2.createCriteria();
            //criteria2.andCodeIn(list);
            criteria2.andNameLike("%"+name+"%");
            criteria2.andTypeLike("%"+type+"%");
           criteria2.andSalesmanEqualTo("");
            List<Customer2Entity> customerEntities = customerService.selectByExample(example2);
            return R.build(customerEntities);
        }catch (Exception e){
        e.printStackTrace();
        return R.buildError(ResultStatusEnum.ERROR);
    }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> delete(String[] ids){
        try {
            List<Integer> list=new ArrayList<>();
            String codes="";
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                codes+=   ids[i].replace("[","").replace("]","")+",";
            }
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            List<String> listCode=new ArrayList<>();
            for(Customer2Entity ce:customerEntities){
                listCode.add(ce.getCode());
            }
            int num = customerService.deleteByExample2(example,listCode);
//删除公共池

           /* List<String> pools=new ArrayList<>();
            String codes="";//客户编码
            for(int i=0;i<customerEntities.size();i++){
                pools.add(customerEntities.get(i).getCode());
                codes+=   customerEntities.get(i).getCode()+",";
            }
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(pools);
            num=customerPoolService.deleteByExample(poolExample);*/
            //日志
            UserEntity user = (UserEntity)this.getBean("user");

            //删除消息
            for (int i = 0; i <listCode.size() ; i++) {
                MessageExample messageExample=new MessageExample();
                MessageExample.Criteria messageExampleCriteria = messageExample.createCriteria();
                messageExampleCriteria.andContentLike("%"+listCode.get(i)+"%");
                messageExampleCriteria.andThemeEqualTo("供应商待审批");

                messageAllService.delMessageByMessage(messageExample);
            }


            Customer2LogEntity record=new Customer2LogEntity();
            record.setCode(codes);
            record.setType("删除");
            record.setOptioner(user.getCode());
            record.setOptionTime(DateUtils.format(new Date()));
            record.setContent("编码："+codes);
            customerLogService.insert(record);

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据id获取客户
     * @param id
     * @return
     */
    @RequestMapping(value = "selectByKey")
    @ResponseBody
    public R<Customer2Entity> selectByKey(Integer id){
        try{
            Customer2Entity customerEntity = customerService.selectByPrimaryKey(id);
            return R.build(customerEntity);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据主键更新
     * @param record
     * @return
     */
    @RequestMapping(value = "updateByKey",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> updateByKey(@RequestBody Customer2Entity record){
        try{
            int num = customerService.updateByPrimaryKeySelective(record);
            //日志
            UserEntity user = (UserEntity)this.getBean("user");
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(record.getCode());
            log.setType("更新");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("编码："+record.getCode());
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 加入公共池，先更新客户表，再更新公共池表
     * @param ids
     * @return
     */
    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> update(String[] ids){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<>();
            String codes="";
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                codes+=ids[i].replace("[","").replace("]","")+",";
            }
            Customer2Entity record=new Customer2Entity();
            record.setSalesman("");
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            int num = customerService.updateByExampleSelective(record,example);

            /*List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman("");
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);*/
            //日志
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(codes);
            log.setType("加入公共池");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+codes);
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 设为自己
     * @param ids
     * @return
     */
    @RequestMapping(value = "setself",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> setself(String[] ids){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            List<Integer> list=new ArrayList<Integer>();
            String codes="";
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                codes+=ids[i].replace("[","").replace("]","")+",";
            }
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            Customer2Entity recode=new Customer2Entity();
            recode.setSalesman(user.getCode());
            int num = customerService.updateByExampleSelective(recode, example);

            /*List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman(user.getCode());
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);*/
            //List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            //日志
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(codes);
            log.setType("设为自己");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("编码："+codes);
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 分配客户
     * @param ids
     * @param saleman
     * @return
     */
    @RequestMapping(value = "savefp",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> savefp(String[] ids,String saleman){
        try{
            List<Integer> list=new ArrayList<Integer>();
            String codes="";
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                codes+=ids[i].replace("[","").replace("]","")+",";
            }
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andIdIn(list);
            Customer2Entity recode=new Customer2Entity();
            recode.setSalesman(saleman);
            int num = customerService.updateByExampleSelective(recode, example);

           /* List<CustomerEntity> customerEntities = customerService.selectByExample(example);
            List<String> poollist=new ArrayList<>();
            String codes="";
            for(int i=0;i<customerEntities.size();i++){
                poollist.add(customerEntities.get(i).getCode());
                codes+=customerEntities.get(i).getCode()+",";
            }
            //更新公共池
            //更新公共池
            CustomerPoolExample poolExample=new CustomerPoolExample();
            CustomerPoolExample.Criteria criteria1 = poolExample.createCriteria();
            criteria1.andCodeIn(poollist);
            CustomerPoolEntity recordpool=new CustomerPoolEntity();
            recordpool.setSalesman(saleman);
            num = customerPoolService.updateByExampleSelective(recordpool, poolExample);*/
//日志
            UserEntity user = (UserEntity)this.getBean("user");
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(codes);
            log.setType("分配客户");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("编码："+codes);
            customerLogService.insert(log);
        return R.build(num);
        }catch (Exception e) {
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 新增,同进插入公共池
     * @param record
     * @return
     */
    @RequestMapping(value = "insert",method = RequestMethod.POST)
    @ResponseBody
    public R<String> insert(@RequestBody Customer2Entity record){
        try{
            //获取登录用户
            UserEntity user = (UserEntity)this.getBean("user");
            //创建者、修改者
            record.setCreater(user.getCode());

            //日志
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(record.getCode());
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("编码："+record.getCode());

            //检测 供应商编码 供应商简称 供应商名称 是否重复
            Integer type=0;//type 1：新增 2：修改
            Integer id=record.getId();
            if (id !=null){
                type=2;
            }else {
                type=1;
            }
            String flag= isRepeat(id,record.getName(),record.getAbbreviation(),record.getCode(),record.getPaymentAccountNo(),type);
            switch (flag){
                case "code":
                    return R.buildCustomize(-100001,"供应商编码重复");
                case "abbreviation":
                    return R.buildCustomize(-100001,"供应商简称重复");
                case "name":
                    return R.buildCustomize(-100001,"供应商名称重复");
                case "paymentAccountNo":
                    return R.buildCustomize(-100001,"供应商代码重复");
            }

            if(record.getId() !=null){
                //更新主信息
                customerService.updateByPrimaryKeySelective(record);

                //日志
                log.setType("更新");
                customerLogService.insert(log);
                return R.build(record.getCode()+":"+record.getId());
            }else {
                /*//主信息编号不存在则获取系统时间作为编号
                if(isExit(record.getCode())){
                    record.setCode(System.currentTimeMillis()+"");
                }*/
                record.setCreatetime(new Date());
                //新增主信息
                customerService.insertSelective(record);

                /*
                //插入公共池
                CustomerPoolEntity recordpool=new CustomerPoolEntity();
                recordpool.setSalesman(record.getSalesman());
                recordpool.setCode(record.getCode());
                num = customerPoolService.insert(recordpool);
                */
                if (record.getTempStatus()==2){
                    addMessage(record,user);
                }

                //日志
                log.setType("新增");
                customerLogService.insert(log);
                return R.build(getcode(record.getCode()));
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 新增消息
     * 提交审批 添加到消息表，接收人为财务部管理员(CWB01)
     */
    public void addMessage(Customer2Entity record,UserEntity user) throws ParseException {
        List<String> adminCode = messageAllService.getFinanceDeptAdmin();
        EditMessageReq req=new EditMessageReq();
        req.setTheme("供应商待审批");
        req.setReceiverCode(StringUtils.join(adminCode,","));
        req.setMessageType(4);
        req.setContent("供应商名称为："+record.getName()+
                "，供应商代码为："+record.getPaymentAccountNo()+
                "，供应商编码为："+record.getCode()+
                "，供应商简称为："+record.getAbbreviation());
        messageAllService.editMessage(req,user.getName(),user.getCode());
    }
    /**
     * 检测 供应商编码 供应商简称 供应商名称 供应商代码 是否重复
     * @param name
     * @param abbreviation
     * @param code
     * @param type 1：新增 2：修改
     * @return
     */
    private String isRepeat(Integer id,String name, String abbreviation, String code,String paymentAccountNo,Integer type){
        if (StringUtils.isNotEmpty(code)){
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andCodeEqualTo(code);
            List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            if (customerEntities.size()>0){
                if (type==1){
                    return "code";
                }
                if (type==2){
                    for (Customer2Entity p:customerEntities){
                        if (!p.getId().equals(id)){
                            return "code";
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(abbreviation)){
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andAbbreviationEqualTo(abbreviation);
            List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            if (customerEntities.size()>0){
                if (type==1){
                    return "abbreviation";
                }
                if (type==2){
                    for (Customer2Entity p:customerEntities){
                        if (!p.getId().equals(id)){
                            return "abbreviation";
                        }
                    }
                }
            }

        }
        if (StringUtils.isNotEmpty(name)){
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andNameEqualTo(name);
            List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            if (customerEntities.size()>0){
                if (type==1){
                    return "name";
                }
                if (type==2){
                    for (Customer2Entity p:customerEntities){
                        if (!p.getId().equals(id)){
                            return "name";
                        }
                    }
                }
            }

        }

        if (StringUtils.isNotEmpty(paymentAccountNo)){
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();
            criteria.andPaymentAccountNoEqualTo(paymentAccountNo);
            List<Customer2Entity> customerEntities = customerService.selectByExample(example);
            if (customerEntities.size()>0){
                if (type==1){
                    return "paymentAccountNo";
                }
                if (type==2){
                    for (Customer2Entity p:customerEntities){
                        if (!p.getId().equals(id)){
                            return "paymentAccountNo";
                        }
                    }
                }
            }

        }

        return "";
    }
    private  boolean isExit(String code){
        Customer2Example example=new Customer2Example();
        Customer2Example.Criteria criteria = example.createCriteria();
       criteria.andCodeEqualTo(code);
        List<Customer2Entity> customerEntities = customerService.selectByExample(example);
        return customerEntities.size()==0?false:true;
    }
    private  String  getcode(String code){
        Customer2Example example=new Customer2Example();
        Customer2Example.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        List<Customer2Entity> customerEntities = customerService.selectByExample(example);
        return customerEntities.get(0).getCode()+":"+customerEntities.get(0).getId();
    }

    /**
     * 获取所有用户
     * @return
     */
    @RequestMapping(value = "getusers",method = RequestMethod.POST)
    @ResponseBody
    public R<List<UserEntity>> getusers(){
        try {
            UserEntityExample example=new UserEntityExample();
            example.createCriteria();
            List<UserEntity> userEntities = userService.selectByExample(example);
            return R.build(userEntities);
        } catch (Exception e){
        e.printStackTrace();
        return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取所有供应商
     * @return
     */
    @RequestMapping(value = "getAllGys")
    @ResponseBody
    public R<List<Customer2Entity> >  getAllGys(){
        try{
            Customer2Example example=new Customer2Example();
            Customer2Example.Criteria criteria = example.createCriteria();

            List<Customer2Entity> customer2Entities = customerService.selectByExample(example);
            return R.build(customer2Entities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    private boolean isAdmin( UserEntity user){
        // if(usercode.indexOf("admin") !=-1)
       // return user.getRoles().indexOf("admin") !=-1 || user.getCode().equals("admin");
        return user.getRoles().indexOf("admin") !=-1 || user.getCode().equals("admin");
    }

    /**
     * 判断是否是管理员
     * @return
     */
    @RequestMapping(value = "isGLY")
    @ResponseBody
    public R<Boolean> isGLY(){
        try{
            UserEntity user = (UserEntity)this.getBean("user");
            boolean tf=isAdmin(user);
            return R.build(tf);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据code获取id
     * @param code
     * @return
     */
    @RequestMapping(value = "getIdBycode")
    @ResponseBody
    public  R<Integer> getIdBycode(String code){
        try{
           /* CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andCodeLike("%"+code+"%");
            List<CustomerEntity> customerEntities = customerService.selectByExample(example);*/
            Customer2Entity ce=new Customer2Entity();
            ce.setCode(code);
            List<Customer2Entity> customerEntities =customerService.selectByMap2(ce);
            Integer id=0;
            if(customerEntities.size()>0){
                id=customerEntities.get(0).getId();
            }
            return R.build(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 保存共享供应商
     * @param usercode
     * @param codes
     * @return
     */
    @RequestMapping(value = "saveshare",method = RequestMethod.POST)
    @ResponseBody
    public R<Boolean> saveshare(String usercode,String[] codes ){
        try{
            int num=0;
            CustomerShareEntity record=new CustomerShareEntity();
            record.setUsercode(usercode);
            for(int i=0;i<codes.length;i++){
                String code=codes[i].replace("[","").replace("]","").replace("\"","");
                record.setCode(code);
                record.setType(2);
                num=customerShareService.insertSelective(record);
            }

            return R.build(num >0?true:false);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    private String getcodes(String usercode){
        String obj="''";
        //不是管理员
        CustomerShareExample example=new CustomerShareExample();
        CustomerShareExample.Criteria criteria = example.createCriteria();
        criteria.andUsercodeEqualTo(usercode);
        criteria.andTypeEqualTo(2);
        List<CustomerShareEntity> customerShareEntities = customerShareService.selectByExample(example);
        for(int i=0;i<customerShareEntities.size();i++){
            obj+=",'"+customerShareEntities.get(i).getCode()+"'";
        }

        return  obj;
    }

    /**
     * 查询验货公司name和code
     * @return 验货公司列表
     */
    @RequestMapping(value = "getAllInspectUnit")
    @ResponseBody
    @ApiOperation(value = "查询验货公司name和code", notes = "查询验货公司name和code", httpMethod = "POST")
    public R<List<SelectVo>> getAllInspectUnit(){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                List<SelectVo> allList = customerService.getAllList();
                if (allList==null){
                    return  R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
                }
                return R.build(allList);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 发起审批工作流
     * @return
     */
    @RequestMapping(value = "startProcess")
    @ResponseBody
    public R<String> startProcess(Integer id){
        try {
            //去掉审批流程，采用伪审批
          /*  UserEntity user = (UserEntity)this.getBean("user");
            UserEntityExample example=new UserEntityExample();
            UserEntityExample.Criteria criteria = example.createCriteria();
            criteria.andRolesLike("%gysbzr%");
            List<UserEntity> userEntities = userService.selectByExample(example);
            //  List<String> list=new ArrayList<>();
            String hxspr="";
            for(int i=0;i<userEntities.size();i++){
                if(i==userEntities.size()-1){
                    hxspr+=userEntities.get(i).getCode();
                }else{
                    hxspr+=userEntities.get(i).getCode()+",";
                }

            }
            Map<String ,Object> map =new HashMap<>();
            map.put("gysbzr",hxspr);
            String processid = ProcessService.startProcess("supplier",id+"",map,user.getCode());*/
            Customer2Entity re=new Customer2Entity();
            re.setId(id);
            re.setSpstatus("2");//1:审批中；2：审批通过；0：草稿
            int num = customerService.updateByPrimaryKeySelective(re);
           /* ProcessCustomer2Entity record=new ProcessCustomer2Entity();
            record.setCustomerid(id);
            record.setProcessid(processid);
            int num = processCustomerService.insert(record);*/
            return R.build(num+"");
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 按code查询验货公司
     * @return 验货公司
     */
    @RequestMapping(value = "selectByCode")
    @ResponseBody
    @ApiOperation(value = "按code查询验货公司", notes = "按code查询验货公司", httpMethod = "POST")
    public R<Customer2Entity> selectByCode(String code){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                Customer2Entity customer2Entity = customerService.selectByCode(code);
                return R.build(customer2Entity);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "updateHByKey" )
    @ResponseBody
    public R<Integer> updateHByKey( String id,String status,Integer tempStatus){
        try{
            Customer2Entity record=new Customer2Entity();
            record.setId(Integer.parseInt(id));
            record.setStatus(status);
            record.setTempStatus(tempStatus);


            //审批通过时 并且只有潜在供应商代码为空。获取最大供应商代码加1 存储
            Customer2Entity entity = customerService.selectByPrimaryKey(Integer.parseInt(id));
            if (tempStatus==Integer.valueOf(3)){
                //获取供应商类型名称
                DictionaryEntity dictionaryEntity = dictionary2Service.selectByParam(6, 36, entity.getType());
                //类型以"潜在" 开头
                if (dictionaryEntity.getName().startsWith("潜在") ){
                    //供应商代码
                    String maxPaymentAccountNo = customerService.getMaxPaymentAccountNo();
                    long anInt = Long.parseLong(maxPaymentAccountNo)+1;
                    record.setPaymentAccountNo(anInt+"");
                }

                //潜在供应商审批通过时
                // 1、潜在供应商--运动营养（type=3） 换成 合作供应商--运动营养（type=1）
                // 2、潜在供应商--化妆品（type=4） 换成 合作供应商--化妆品（type=2）
                if (entity.getType().equals("3")){
                    record.setType("1");
                }
                if (entity.getType().equals("4")){
                    record.setType("2");
                }
            }


            log.info("修改后的数据{}",record.toString());
            int num = customerService.updateByPrimaryKeySelective(record);

            UserEntity user = (UserEntity)this.getBean("user");
            if (record.getTempStatus()==Integer.valueOf(2)){
                addMessage(entity,user);
            }

            //日志
            Customer2LogEntity log=new Customer2LogEntity();
            log.setCode(record.getCode());
            log.setType("更新");
            log.setOptioner(user.getCode());
            log.setOptionTime(DateUtils.format(new Date()));
            log.setContent("客户编码："+record.getCode());
            customerLogService.insert(log);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 供应商账期详情--分页
     * @return
     */
    @RequestMapping("supAccDeCollListByPage")
    @ResponseBody
    public R supAccDeCollListByPage(supAccDeCollReq req){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            if (StringUtils.isEmpty(req.getSalesmanCode()) && StringUtils.isEmpty(req.getDeptSalesmanCode()) ){
                req.setSalesmanCode(user.getCode());
            }
            PageInfo<supAccDeCollRes> pageInfo=customerService.supAccDeColl(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 供应商账期详情--导出
     * @return
     */
    @RequestMapping("supAccDeCollExport")
    @ResponseBody
    public R supAccDeCollExport(supAccDeCollReq req){
        try {
            JSONObject info = customerService.supAccDeCollExport(req);
            return R.build(info);
        } catch (Exception e) {
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }




    /**
     * 供应商采购金额及出货金额统计--分页
     * @return
     */
    @RequestMapping("supAmountAndPurAmountListByPage")
    @ResponseBody
    public R supAmountAndPurAmountListByPage(supAmountAndPurAmountReq req){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            if (StringUtils.isEmpty(req.getSalesmanCode()) && StringUtils.isEmpty(req.getDeptSalesmanCode()) ){
                req.setSalesmanCode(user.getCode());
            }
            PageInfo<supAmountAndPurAmountRes> pageInfo=customerService.supAmountAndPurAmountPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 供应商采购金额及出货金额统计--导出
     * @return
     */
    @RequestMapping("supAmountAndPurAmountExport")
    @ResponseBody
    public R supAmountAndPurAmountExport(supAmountAndPurAmountReq req){
        try {
            JSONObject info = customerService.supAmountAndPurAmountExport(req);
            return R.build(info);
        } catch (Exception e) {
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }



    /**
     * 查询供应商属性
     * @param supplierCode 供应商
     * @return
     */
    @RequestMapping("selectSupplierInfo")
    @ResponseBody
    public R selectSupplierInfo(String supplierCode){
        try {
            if (StringUtils.isEmpty(supplierCode)){
                return R.build(ResultStatusEnum.PARAMETER_ERROR);
            }
            Customer2Entity entity=customerService.selectByCode(supplierCode);
            return R.build(entity);
        }catch (Exception e){
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 设置供应商属性
     * @param supplierCode 供应商
     * @param accountPeriod 账期
     * @param paymentTypeCode 付款类型
     * @return
     */
    @RequestMapping("updateSupplierInfo")
    @ResponseBody
    public R updateSupplierInfo(String supplierCode,String accountPeriod,String paymentTypeCode){
        try {
            if (StringUtils.isEmpty(supplierCode)){
                return R.build(ResultStatusEnum.PARAMETER_ERROR);
            }
            Customer2Entity entity=customerService.selectByCode(supplierCode);
            entity.setAccountPeriod(accountPeriod);
            entity.setSourceOfCustomers(paymentTypeCode);
            customerService.updateByPrimaryKey(entity);

            return R.build(ResultStatusEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return R.build(ResultStatusEnum.ERROR);
        }
    }


    /*
     * 查询是否为财务部管理员,用于审批供应商
     * */
    @GetMapping("/isMsn")
    @ResponseBody
    public R isMsn(){
        UserEntity user = (UserEntity) this.getBean("user");
        String deptCode=user.getDepartmentCode();
        //财务部编码
        String code="CWB01";
        if (StringUtils.isNotEmpty(deptCode) && deptCode.equals(code)){
            return R.build(user.getMsn());
        }
        return R.build("否");
    }
    /*
     * 查询是否为财务部
     * */
    @GetMapping("/isFinance")
    @ResponseBody
    public R isFinance(){
        UserEntity user = (UserEntity) this.getBean("user");
        String deptCode=user.getDepartmentCode();
        //财务部编码
        String code="CWB01";
        if (StringUtils.isNotEmpty(deptCode) && deptCode.equals(code)){
            return R.build(true);
        }
        return R.build(false);
    }

    /**
     * 获取待审批的供应商
     * @param
     * @return
     */
    @RequestMapping(value = "getPendingSupplierList")
    @ResponseBody
    public  R getPendingSupplierList(){
        try{
            log.info("获取待审批的供应商 ");
            UserEntity user = (UserEntity) this.getBean("user");
            //财务部编码
            List<Customer2Entity> customer2Entities =new ArrayList<>();
            if (user.getCode().equals("RKB004")){
                Customer2Example example=new Customer2Example();
                Customer2Example.Criteria criteria = example.createCriteria();
                criteria.andTempStatusEqualTo(2);
                customer2Entities = customerService.selectByExample(example);
                return R.build(customer2Entities);
            }
            return R.build(customer2Entities);
        }catch (Exception e){
            log.info("获取待审批的供应商异常 {}",e.getMessage());
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }


    /*
     * 查询是否含有 管理员 角色
     * */
    @GetMapping("/isAdmin")
    @ResponseBody
    public R isAdmin(){
        UserEntity user = (UserEntity) this.getBean("user");
        if (user.getRoles().contains("admin")){
            return R.build(true);
        }
        return R.build(false);
    }

}
